
package com.ikamobile.flickrer;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

public class FlickrApi {

    private static final String API_KEY = "ead1a52dcfb8bfe0a073dfe96b1fca9b";

    public static List<Photo> getPhotosSlow(String keywords) throws IOException,
            JSONException {
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            // do nothing
        }
        return getPhotos(keywords);
    }

    public static List<Photo> getPhotos(String keywords) throws IOException,
            JSONException {
        String url;
        if (keywords != null)
            url = String
                    .format("http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=%s&text=%s&format=json",
                            API_KEY, URLEncoder.encode(keywords));
        else
            url = String
                    .format("http://api.flickr.com/services/rest/?method=flickr.photos.getRecent&api_key=%s&format=json",
                            API_KEY);
        InputStream is = new URL(url).openStream();
        String json = is2s(is);
        json = json.substring("jsonFlickrApi(".length(), json.length() - 1);
        JSONObject root = new JSONObject(json);
        if (!"ok".equals(root.getString("stat")))
            throw new IOException("stat!=ok");
        JSONArray photosJson = root.getJSONObject("photos").getJSONArray("photo");
        int count = photosJson.length();
        ArrayList<Photo> photos = new ArrayList<Photo>(count);
        for (int i = 0; i < count; i++)
            photos.add(createPhoto(photosJson.getJSONObject(i)));
        return photos;
    }

    private static Photo createPhoto(JSONObject photoJson) throws JSONException {
        String id = photoJson.getString("id");
        int farm = photoJson.getInt("farm");
        String secret = photoJson.getString("secret");
        String server = photoJson.getString("server");
        String title = photoJson.getString("title");
        return new Photo(id, farm, secret, server, title);
    }

    public static String is2s(InputStream is) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null)
            sb.append(line).append("\n");
        return sb.toString();
    }

}
